import json
import logging
import os
import time
from tkinter import Tk
from tkinter.ttk import Notebook
from datetime import date, timedelta
from tkinter.messagebox import askokcancel
from .config_tab import ConfigTab
from .brush_tab import BrushTab
from .account_tab import AccountTab
from taobao_check.brush import PLATFORMS
from taobao_check.tools import PATH, URL, Config, ENTOZH, check_chrome_driver_update, clear_log, \
    kill_process, get_child_process, get_gitee_json, run_async


class UI(Tk):
    env_ok = False
    init_ok = False
    end = False
    check = None
    tabs = []
    burshs = []
    memory_limit = 500
    config_tab = None

    def __init__(self, name, version):
        Tk.__init__(self)
        self.name = name
        self.version = version
        self.notebook = Notebook(self)
        self.config = Config()
        self.set_ui()
        self.init_env()
        self.center_window()
        self.protocol('WM_DELETE_WINDOW', self.quit)
        self.check_update()
        # self.timing_kill_chrome()

    def set_ui(self):
        self.maxsize(1200, 900)
        self.minsize(600, 400)
        self.set_title()
        if PATH.icon.is_file():
            self.iconbitmap(PATH.icon)

    def set_title(self, username=None, expire=None):
        if username and expire:
            self.title(f"{self.name}V{self.version} —— 【{username}】会员到期时间:【{expire}】")
        elif username:
            self.title(f"{self.name}V{self.version} —— 【{username}】")
        elif expire:
            self.title(f"{self.name}V{self.version} —— 会员到期时间:【{expire}】")
        else:
            self.title(f"{self.name}V{self.version}")

    @run_async
    def init_env(self):
        try:
            clear_log()
            self.set_tab()
            self.print_log("启动程序.")
            self.env_ok = check_chrome_driver_update(self.print_log)
            if not self.env_ok:
                self.init_ok = True
                return
            if not self.check_permission():
                self.init_ok = True
                return

            for brush in self.burshs:
                brush.start()

        except Exception as e:
            self.print_log(f"软件初始化失败，原因是: {e}")
            logging.exception(e)
            self.print_log("请重启软件试试.\n")
            self.env_ok = False

        self.init_ok = True

    def set_tab(self):
        """使用了 Notebook 组件，有利于后期添加新的功能"""
        """设置可用平台"""
        platform = self.config.user.platform
        exclude = self.config.user.exclude if "exclude" in self.config.user else []
        if platform == "all":
            platform = {p: PLATFORMS[p] for p in PLATFORMS if p not in exclude}
        else:
            platform = {p: PLATFORMS[p] for p in platform if p not in exclude}

        for name, brush in platform.items():
            tab = BrushTab(name)
            self.notebook.add(tab, text=f" {ENTOZH[name]} ")
            self.tabs.append(tab)
            self.burshs.append(brush(self.config, tab))

        self.notebook.add(AccountTab(self.version, self.config), text=f" 账号 ")
        self.config_tab = ConfigTab(self.version, self.config, self)
        self.notebook.add(self.config_tab, text=f" 设置 ")

        self.notebook.pack()

    def check_permission(self):
        if not self.config.user.name:
            self.print_log(f"用户【{self.config.account.username}】没有使用此软件的权限。")
            self.print_log(f"请确保拥有互联网连接。")
            self.print_log(f"请修改账号信息或者联系管理员添加。")
            return False

        self.set_title(self.config.user.name)
        expire = self.config.user.expire
        if expire != "none":
            expire = date(*expire)
            self.set_title(self.config.user.name, expire)
            if expire - date.today() < timedelta(0):
                self.print_log(f"用户【{self.config.account.username}】会员已到期。")
                self.print_log(f"请联系管理员进行续费。")
                return False

        return True

    def print_log(self, log, debug=False):
        print(log)
        for tab in self.tabs:
            try:
                tab.print_log(log, debug)
            except:
                print(log)

    def center_window(self):
        """窗口居中"""
        self.update()
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        width = self.winfo_width()
        height = self.winfo_height()
        size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2-50)
        self.geometry(size)
        self.resizable(False, False)

    @run_async
    def check_update(self):
        """
        TODO: 更新检测加入基本包的检测
        """
        while True:
            if not self.config_tab:
                time.sleep(1)
                continue
            config = get_gitee_json(URL.update)
            if not config:
                time.sleep(60)
                continue
            config = json.loads(config)
            self.config_tab.set_update(config)
            if "msg" in config:
                for tab in self.tabs:
                    tab.set_msg(config['msg'])

            time.sleep(3600)

    def quit(self):
        if askokcancel("退出", "是否确定退出?"):
            self.print_log("软件退出。", debug=True)
            self.destroy()
            start = time.time()
            while not self.init_ok and (time.time() - start < 30):
                time.sleep(0.1)

            for brush in self.burshs:
                try:
                    brush.quit(True)
                except:
                    pass

            chromes = get_child_process(os.getpid())
            for _, pid in chromes:
                kill_process(pid)
